<?php
namespace Todo\Service;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class TokenService extends BaseService
{
    private static $__INSTANCE = null;

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new TokenService();

        return self::$__INSTANCE;
    }

    
    /**
     * 获取一个空令牌
     * @return string
     */
    public function grantToken($userId, $scope='public', $ip = ''){

        $data = array(
            'user_id' => $userId,
            'scope'   => $scope,
            'ip'      => $ip ? $ip :get_client_ip()
        );
        $model = D('Todo/Sys/Token');
        $data = $model->create($data);
        if($data && $model->add($data)) return $data['code'];

        return false;
    }

    /** 更新空令牌的用户信息
     * @param string $token 令牌代码
     * @param int $userId 用户ID
     * @param int $terminalId 终端ID
     * @return bool
     */
    public function updateTokenUser($token, $userId, $terminalId){
        $data = array(
            'user_id' => $userId,
            'terminal_id' => $terminalId,
        );
        return D('Todo/Sys/Token')->where(array('code'=>$token))->save($data) !== false ;
    }

    /** 查询令牌信息
     * @param string $token 令牌代码
     * @return array
     */
    public function getToken($token){
        $key = 'token_code_'.$token;
        $info = S($key);
        if(!$info) $info = D('Todo/Sys/Token')->where(array('code'=>$token))->find(); //缓存中没有，则查询数据库
        if($info && $info['is_expired'] == 0 && strtotime($info['create_time']) + C('TOKEN_EXPIRE') > NOW_TIME) //令牌存在并没有过期
        {
            if($info['user_id']) S($key, $info); //绑定用户的token进入缓存
            return $info;
        }

        S($key, null);
        D('Common/Sys/Token')->where(array('code'=>$token))->save(array('is_expired'=>1));
        return false;
    }

    /**
     * 验证令牌权限
     * @param string $token 令牌代码
     * @param string $scope 权限代码
     * @return bool
     */
    public function checkScope($token, $scope){
        $tokenInfo = $this->getToken($token);
        if(!$tokenInfo || !$tokenInfo['scope'])
        {
            $this->setError('非法令牌或者已经过期');
            return false;
        }

        $scopes = explode(',', $tokenInfo['scope']);
        if(in_array($scope, $scopes)) return true;

        $this->setError('您没有权限');
        return false;
    }

}